import {defineStore} from 'pinia'
import {UserLogin} from '@/apis/user/index'
import {mergeCart} from '@/apis/cart/index'
import useCartStore from './cartStore'
import { SETTOKEN,SETUSERINFO,GETTOKEN,GETUSERINFO,REMOVEINFO } from '@/utils/Token'
const UseUserStore = defineStore('UserStore',{
    state:()=>{
        return {
            UserInfo:GETUSERINFO() || '',
            token:GETTOKEN() || ''
        }
    },
    actions:{
        //登录
        async UserLogin(data){
            try {
                let cartStore = useCartStore()
                let res = await UserLogin(data)
                SETUSERINFO(res.result)
                SETTOKEN(res.result.token)
                this.UserInfo = GETUSERINFO()
                this.token =GETTOKEN()
                //合并数据
                let mapArr = cartStore.cartList.map(item=>{
                    return {
                        skuId:item.skuId,
                        selected:item.selected,
                        count:item.count
                    }
                })
                await mergeCart(mapArr)
            } catch (error) {
                return new Promise.reject(error)
            }
        },
        //登出
        UserLogout() {
            this.UserInfo = ''
            this.token = ''
            REMOVEINFO('token')
            REMOVEINFO('UserInfo')
        }
    },
    getters:{

    }
})

export default UseUserStore